<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="../../plugins/element-ui/index.css"/>
    <link rel="stylesheet" href="../../styles/common.css"/>
    <link rel="stylesheet" href="../../styles/page.css"/>
    <style>
        .card-detail {
            padding: 20px;
        }

        .detail-item {
            margin-bottom: 20px;
        }

        .detail-item label {
            font-weight: bold;
        }

        .card-image {
            max-width: 100%;
            height: 175px;
            border-radius: 4px;
            width: 200px;
        }

        .el-button--text {
            /* color: red; */
            color: lightblue;
            margin-top: 15px;
            margin-left: 30px;
        }

        .el-button--text :hover {
            color: aqua;
        }

        .container {
            max-width: 1240px;
            margin: 0 auto;
            padding: 20px;
            font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
            background-color: #f5f7fa;
        }

        .avatar-uploader .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }

        .avatar-uploader .el-upload:hover {
            border-color: #409EFF;
        }

        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            line-height: 178px;
            text-align: center;
        }

        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }

        /* 标题行样式 */
        .detail-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

    </style>
</head>
<body>
<div id="stadium-card-detail-app">
    <div class="container">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
            <h1>会员卡详情</h1>
            <el-button
                    type="primary"
                    size="medium"
                    @click="showEditDialog">
                修改信息
            </el-button>
        </div>
        <el-card class="card-detail">
            <div class="detail-content">
                <el-row :gutter="20">
                    <el-col :span="24">
                        <div class="detail-item">
                            <label>会员卡名称：</label>
                            <span>{{ cardDetail.name }}</span>
                        </div>
                    </el-col>
                    <el-col :span="24">
                        <div class="detail-item">
                            <label>类型：</label>
                            <span>{{ cardDetail.type }}</span>
                        </div>
                    </el-col>
                    <el-col :span="24" v-if="cardDetail.type === '期限卡'">
                        <div class="detail-item">
                            <label>有效期：</label>
                            <span>{{ cardDetail.day }} 天</span>
                        </div>
                    </el-col>
                    <el-col :span="24" v-if="cardDetail.type === '次卡'">
                        <div class="detail-item">
                            <label>使用次数：</label>
                            <span>{{ cardDetail.num }}</span>
                        </div>
                    </el-col>
                    <el-col :span="24">
                        <div class="detail-item">
                            <label>原价：</label>
                            <span>{{ cardDetail.oldPrice }} 元</span>
                        </div>
                    </el-col>
                    <el-col :span="24">
                        <div class="detail-item">
                            <label>售价：</label>
                            <span>{{ cardDetail.price }} 元</span>
                        </div>
                    </el-col>
                    <el-col :span="24">
                        <div class="detail-item">
                            <label>会员卡标签：</label>
                            <span>{{ cardDetail.tags == null || cardDetail.tags == '' ? "暂无标签信息" : formatTags(cardDetail.tags)}}</span>
                        </div>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="24">
                        <div class="detail-item">
                            <label>会员卡备注信息：</label>
                            <span>{{ cardDetail.remark == null || cardDetail.remark == '' ? '暂无备注信息' : cardDetail.remark}}</span>
                        </div>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="24">
                        <div class="detail-item">
                            <label>会员卡图片：</label>
                            <p>
                                <img :src="imageUrl" alt="会员卡图片" class="card-image">
                            </p>
                        </div>
                    </el-col>
                </el-row>
            </div>
        </el-card>
    </div>

    <div class="container">
        <h1>拥有该卡的用户</h1>
        <el-table :data="tableData" stripe class="tableBox" max-height="500px">
            <el-table-column prop="username" label="会员名称" align="center"></el-table-column>
            <el-table-column prop="phone" label="会员电话" align="center"></el-table-column>
            <el-table-column prop="level" label="会员等级" align="center"></el-table-column>
            <el-table-column prop="startTime" label="办卡时间" align="center"></el-table-column>
            <el-table-column prop="remainingTime" label="剩余时间(天)" align="center"></el-table-column>
            <el-table-column prop="endTime" label="到期时间" align="center"></el-table-column>
            <el-table-column prop="status" label="会员卡状态" align="center">
                <template #default="{row}">
                    <el-tag :type="row.isDeleted=='0'?'success':'danger'">
                        {{row.isDeleted=='0'?'可用':'不可用'}}
                    </el-tag>
                </template>
            </el-table-column>
            </el-table-column>
        </el-table>
    </div>

    <el-dialog
            title="修改会员卡信息"
            :visible.sync="editDialogVisible"
            width="50%"
            :close-on-click-modal="false">

        <el-form
                :model="editForm"
                label-width="120px"
                ref="editForm"
                :rules="editRules">

            <el-form-item label="会员卡名称" prop="name">
                <el-input v-model="editForm.name"></el-input>
            </el-form-item>

            <el-form-item label="有效期(天)" prop="day">
                <el-input-number v-model="editForm.day" :min="1"></el-input-number>
            </el-form-item>

            <el-form-item label="使用次数" prop="num">
                <el-input-number v-model="editForm.num" :min="0"></el-input-number>
            </el-form-item>

            <el-form-item label="价格" prop="num">
                <el-input-number v-model="editForm.price" :min="0"></el-input-number>
            </el-form-item>

            <el-form-item label="标签">
                <el-select
                        v-model="editForm.tags"
                        multiple
                        placeholder="请选择标签">
                    <el-option
                            v-for="tag in cardTagList"
                            :key="tag"
                            :label="tag"
                            :value="tag">
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="会员卡内容" prop="content">
                <el-input
                        type="textarea"
                        :rows="3"
                        v-model="editForm.remark"
                        placeholder="请输入会员卡描述内容">
                </el-input>
            </el-form-item>

            <el-form-item label="会员卡图片">
                <el-upload
                        class="avatar-uploader"
                        action="http://localhost:8080/common/upload"
                        :show-file-list="false"
                        :on-success="handleImageUpload"
                        :before-upload="beforeImageUpload">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
    </span>
    </el-dialog>
</div>


<!-- 开发环境版本，包含了有帮助的命令行警告 -->
<script src="../../plugins/vue/vue.js"></script>
<!-- 引入组件库 -->
<script src="../../plugins/element-ui/index.js"></script>
<!-- 引入axios -->
<script src="../../plugins/axios/axios.min.js"></script>
<script src="../../js/request.js"></script>
<script src="../../js/validate.js"></script>
<script src="../../js/index.js"></script>
<script src="../../api/card.js"></script>
<!--<script src="../../api/tags.js"></script>-->

<script>
    let tagsOptions = [];
    new Vue({
        el: '#stadium-card-detail-app',
        data() {
            return {
                cardId: '',
                tagType: "会员卡",
                editDialogVisible: false,
                imageUrl: null,
                editForm: {
                    name: '',
                    day: 0,
                    num: 0,
                    tags: '',
                    content: '',
                    background: ''
                },
                tableData: [],
                cardTagList: [],
                cardDetail: {},
                editRules: {
                    name: [
                        {required: true, message: '请输入会员卡名称', trigger: 'blur'},
                        {min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur'}
                    ],
                    day: [
                        {required: true, message: '请设置有效期', trigger: 'blur'}
                    ],
                }
            };
        },
        computed: {
            rules() {
                return {
                    'name': [
                        {'required': true, 'message': '请填写名称', 'trigger': 'blur'}
                    ],

                    'price': [
                        {
                            'required': true,
                            validator: (rules, value, callback) => {
                                if (!value) {
                                    callback(new Error('请填写价格'))
                                } else {
                                    const reg = /^\d+(\.\d{0,2})?$/;
                                    if (reg.test(value)) {
                                        if (value < 10000) {
                                            callback()
                                        } else {
                                            callback(new Error('价格小于10000'))
                                        }
                                    } else {
                                        callback(new Error('价格格式只能为数字,且最多保留两位小数'))
                                    }
                                }
                            },
                            'trigger': 'blur'
                        }
                    ],
                }
            }
        },
        created() {
            this.cardId = requestUrlParam('cardId');
            this.init();
            this.selectUser();
            getTagListByType("会员卡").then(res => {
                this.cardTagList = res.data || [];
            })
        },
        mounted() {
        },
        methods: {
            async init() {
                // console.log(_this.tags)
                queryCardById(this.cardId).then(res => {
                    console.log(res);
                    if (String(res.code) === '1') {
                        this.cardDetail = {...res.data};
                        this.cardDetail.status = res.data.status == '1'
                        this.imageUrl = `/common/download?name=${res.data.background}`
                        var arr = res.data.tags   //搏击,瑜伽  ->  ['搏击', '瑜伽',]
                        var split = arr.split(",");
                        console.log(split)
                        this.ruleForm.tags = split
                        console.log(arr)
                        console.log(this.ruleForm.tags)
                    } else {
                        this.$message.error(res.msg || '操作失败')
                    }
                })

            },

            beforeImageUpload(file) {
                const isImage = ['image/jpeg', 'image/png'].includes(file.type);
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isImage) {
                    this.$message.error('上传图片只能是 JPG/PNG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传图片大小不能超过 2MB!');
                }
                return isImage && isLt2M;
            },
            handleImageUpload(res, file) {
                if (res.code === 1) {
                    this.imageUrl = URL.createObjectURL(file.raw);
                    // 保存服务器返回的图片路径
                    this.editForm.background = res.data;
                    this.imageUrl = `/common/download?name=${res.data}`;
                } else {
                    this.$message.error('图片上传失败');
                }
            },
            selectUser() {
                getByIdWithUser(this.cardId).then(res => {//请求结果处理
                    if (String(res.code) === '1') {
                        this.tableData = res.data
                        console.log(this.tableData)
                    } else {
                        this.$message.error(res.msg)
                    }
                })
            },

            submitEditForm() {
                console.log(this.editForm)
                this.$refs.editForm.validate(valid => {
                    if (valid) {
                        let tagsStr = '';
                        if (this.editForm.tags && this.editForm.tags.length) {
                            tagsStr = this.editForm.tags.join(',');
                        }
                        // 构造提交数据
                        const submitData = {
                            ...this.editForm,
                            tags: tagsStr,
                            cardId: this.cardId
                        };
                        console.log(submitData)
                        editCardDetail(submitData).then(res => {
                            if (res.code === 1) {
                                this.$message.success('修改成功');
                                this.cardDetail = {
                                    ...this.cardDetail,
                                    ...this.editForm,
                                    background: this.editForm.background,
                                    tags: tagsStr
                                };
                                this.editDialogVisible = false;
                            } else {
                                this.$message.error(res.msg || '修改失败');
                            }
                        }).catch(err => {
                            this.$message.error('请求失败');
                            console.error(err);
                        });
                    }
                })
            },
            handleCheckAllChange(val) {
                this.ruleForm.tags = val ? tagsOptions : []
                this.isIndeterminate = false;
                console.log(this.ruleForm.tags)

            },
            handleCheckedCitiesChange(value) {
                let checkedCount = value.length;
                this.checkAll = checkedCount === this.tags.length;
                this.isIndeterminate = checkedCount > 0 && checkedCount < this.tags.length;
                this.ruleForm.tags = value
                console.log(this.ruleForm.tags)
            },

            handleAvatarSuccess(response, file, fileList) {
                // 拼接down接口预览
                if (response.code === 0 && response.msg === '未登录') {
                    window.top.location.href = '../login/login.html'
                } else {
                    this.imageUrl = `/common/download?name=${response.data}`;
                    this.ruleForm.image = response.data
                }
            },

            onChange(file) {
                if (file) {
                    const suffix = file.name.split('.')[1];
                    const size = file.size / 1024 / 1024 < 2;
                    if (['png', 'jpeg', 'jpg'].indexOf(suffix) < 0) {
                        this.$message.error('上传图片只支持 png、jpeg、jpg 格式！');
                        this.$refs.upload.clearFiles();
                        return false
                    }
                    if (!size) {
                        this.$message.error('上传文件大小不能超过 2MB!');
                        return false
                    }
                    return file
                }
            },
            showEditDialog() {
                this.editDialogVisible = true;
                queryCardById(this.cardId).then(res => {
                    if (res.code === 1) {
                        let tags = [];
                        if (res.data.tags) {
                            // 处理可能的格式：1. 纯字符串"标签1,标签2" 2. JSON字符串["标签1","标签2"]
                            try {
                                tags = JSON.parse(res.data.tags);
                                if (!Array.isArray(tags)) {
                                    tags = res.data.tags.split(',').map(t => t.trim());
                                }
                            } catch (e) {
                                tags = res.data.tags.split(',').map(t => t.trim());
                            }
                        }
                        this.editForm = {
                            ...res.data,
                            tags: tags  // 确保是数组格式
                        };
                        console.log(this.editForm)
                    }
                    // this.editDialogVisible = true;
                })
            },
            goBack() {
                window.parent.menuHandle({
                    id: '3',
                    url: '/page/stadium/detail.html',
                    name: '店铺详情'
                }, false)
            },
            // 格式化
            formatTags(tags) {
                if (!tags) return '';

                if (Array.isArray(tags)) {
                    return tags.join(', ');
                }

                if (tags.startsWith('[')) {
                    try {
                        const arr = JSON.parse(tags);
                        return arr.join(', ');
                    } catch (e) {
                        return tags.replace(/[\[\]"]+/g, '');
                    }
                }

                // 其他情况直接返回
                return tags;
            },

        }
    })
</script>
</body>
</html>